<?php

/**
 * Created by PhpStorm.
 * User: tong
 * Date: 2021/1/8
 * Time: 9:46
 */

namespace MyTool\Logger;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;

class PrintLoggerTool
{
    /**
     * 输出日志
     * @param string $method ____METHOD__  这个魔术方法
     * @param $getMessage
     * @param $level int 打印级别  1-error 异常信息   2-notice 正常显示  3-info 打印普通信息
     */
    public static function printLogger(string $method, $getMessage, $level = 1)
    {
        $func = self::level($level);
        $debugInfo = Context::get('debug_info');
        if (env("APP_ENV", 'prod') != 'prod') {
            $debugInfo = 1;
        }
        if ($level == 3 && $debugInfo != 1) {
            return;
        }
        $link = Context::get('g_header')['link'] ?? '';
        // {时间}链式{方法体}响应信息
        $dataMsg = "{" . date("Y-m-d H:i:s") . "}" . $link . "{" . $method . "}" . ':响应信息:' . $getMessage;
        switch (1) {
            case env("CONSOLE_WRITE_LOG", 'false') == 'true':
                self::writeLog($dataMsg, $func);
                self::consoleLog($dataMsg, $func);
                break;
            case env("DEBUG_OUT_MODEL", 'default') != 'default':
                self::writeLog($dataMsg, $func);
                break;
            default:
                self::consoleLog($dataMsg, $func);
                break;
        }
    }

    /**
     * 写入log文件
     * @param $dataMsg
     * @param $func
     */
    private static function writeLog($dataMsg, $func)
    {
        $container = ApplicationContext::getContainer();
        /** @var LoggerFactory $loggerLog */
        $loggerLog = $container->get(LoggerFactory::class)->get(env("APP_NAME"), 'file');
        $loggerLog->$func($dataMsg);
    }

    /**
     * 日志打印在控制台
     * @param $dataMsg
     * @param $func
     */
    private static function consoleLog($dataMsg, $func)
    {
        $container = ApplicationContext::getContainer();
        /** @var StdoutLoggerInterface $loggerLog */
        $loggerLog = $container->get(StdoutLoggerInterface::class);
        $loggerLog->$func($dataMsg);
    }

    /**
     * 打印级别
     * @param $level
     * @return string
     */
    private static function level($level)
    {
        $data = [
            1 => 'error',
            2 => 'notice',
            3 => 'info'
        ];
        return $data[$level] ?? $data[1];
    }
}
